<template>
  <view class="groupon-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <text class="header-title">团购管理</text>
        <view class="header-actions">
          <uni-icons type="settings" size="20" color="#fff" @click="handleSettings" />
        </view>
      </view>
    </view>

    <!-- 数据概览卡片 -->
    <view class="overview-section">
      <view class="overview-card">
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.totalActivities }}</text>
          <text class="overview-label">活动总数</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">{{ overviewData.totalOrders }}</text>
          <text class="overview-label">订单总数</text>
        </view>
        <view class="overview-item">
          <text class="overview-value">¥{{ formatPrice(overviewData.totalRevenue) }}</text>
          <text class="overview-label">总销售额</text>
        </view>
      </view>
    </view>

    <!-- 功能模块网格 -->
    <view class="modules-section">
      <view class="modules-grid">
        <view 
          class="module-card" 
          v-for="module in modules" 
          :key="module.key"
          @click="navigateToModule(module)"
        >
          <view class="module-icon">
            <uni-icons :type="module.icon" size="32" :color="module.color" />
          </view>
          <text class="module-title">{{ module.title }}</text>
          <text class="module-desc">{{ module.desc }}</text>
          <view class="module-badge" v-if="module.badge">
            <text class="badge-text">{{ module.badge }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 快捷操作区 -->
    <view class="quick-actions">
      <text class="section-title">快捷操作</text>
      <scroll-view class="actions-scroll" scroll-x>
        <view class="actions-list">
          <view 
            class="action-item" 
            v-for="action in quickActions" 
            :key="action.key"
            @click="handleQuickAction(action)"
          >
            <view class="action-icon">
              <uni-icons :type="action.icon" size="24" color="#1890FF" />
            </view>
            <text class="action-text">{{ action.text }}</text>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 今日数据统计 -->
    <view class="today-stats">
      <text class="section-title">今日数据</text>
      <view class="stats-card">
        <view class="stats-row">
          <view class="stats-item">
            <text class="stats-label">新增订单</text>
            <text class="stats-value">{{ todayStats.newOrders }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">核销数量</text>
            <text class="stats-value">{{ todayStats.verifiedCount }}</text>
          </view>
        </view>
        <view class="stats-row">
          <view class="stats-item">
            <text class="stats-label">销售金额</text>
            <text class="stats-value">¥{{ formatPrice(todayStats.salesAmount) }}</text>
          </view>
          <view class="stats-item">
            <text class="stats-label">活跃用户</text>
            <text class="stats-value">{{ todayStats.activeUsers }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { statisticsApi } from '@/api/groupbuy';
import type { StatisticsData } from '@/types/groupbuy';

// 数据概览
const overviewData = ref<StatisticsData>({
  totalActivities: 0,
  totalOrders: 0,
  totalRevenue: 0,
});

// 今日统计数据
const todayStats = ref({
  newOrders: 0,
  verifiedCount: 0,
  salesAmount: 0,
  activeUsers: 0,
});

// 功能模块配置
const modules = ref([
  {
    key: 'activity',
    title: '团购活动',
    desc: '活动管理',
    icon: 'gift',
    color: '#1890FF',
    path: '/pages/groupons/activity/index',
    badge: '',
  },
  {
    key: 'order',
    title: '订单管理',
    desc: '订单查看',
    icon: 'list',
    color: '#52C41A',
    path: '/pages/groupons/order/index',
    badge: '',
  },
  {
    key: 'statistics',
    title: '统计分析',
    desc: '数据报表',
    icon: 'bars',
    color: '#FA8C16',
    path: '/pages/groupons/statistics/index',
    badge: '',
  },
  {
    key: 'verify',
    title: '核销管理',
    desc: '券码核销',
    icon: 'scan',
    color: '#722ED1',
    path: '/pages/groupons/verify/index',
    badge: '',
  },
]);

// 快捷操作配置
const quickActions = ref([
  {
    key: 'newActivity',
    text: '新建活动',
    icon: 'plus',
    action: 'createActivity',
  },
  {
    key: 'scanVerify',
    text: '扫码核销',
    icon: 'scan',
    action: 'scanVerify',
  },
  {
    key: 'orderSearch',
    text: '订单查询',
    icon: 'search',
    action: 'searchOrder',
  },
  {
    key: 'dataExport',
    text: '数据导出',
    icon: 'download',
    action: 'exportData',
  },
]);

// 格式化价格
const formatPrice = (price: number) => {
  return (price / 100).toFixed(2);
};

// 加载数据概览
const loadOverviewData = async () => {
  try {
    const res = await statisticsApi.getData({});
    if (res.success) {
      overviewData.value = res.data;
    }
  } catch (error) {
    console.error('加载概览数据失败:', error);
  }
};

// 加载今日统计
const loadTodayStats = async () => {
  try {
    const today = new Date();
    const startTime = new Date(today.getFullYear(), today.getMonth(), today.getDate()).toISOString();
    const endTime = new Date(today.getFullYear(), today.getMonth(), today.getDate() + 1).toISOString();
    
    const res = await statisticsApi.getData({ startTime, endTime });
    if (res.success) {
      todayStats.value = {
        newOrders: res.data.newOrders || 0,
        verifiedCount: res.data.verifiedCount || 0,
        salesAmount: res.data.salesAmount || 0,
        activeUsers: res.data.activeUsers || 0,
      };
    }
  } catch (error) {
    console.error('加载今日统计失败:', error);
  }
};

// 导航到模块页面
const navigateToModule = (module: any) => {
  uni.navigateTo({
    url: module.path,
  });
};

// 处理快捷操作
const handleQuickAction = (action: any) => {
  switch (action.action) {
    case 'createActivity':
      uni.navigateTo({
        url: '/pages/groupons/activity/detail?mode=create',
      });
      break;
    case 'scanVerify':
      uni.navigateTo({
        url: '/pages/groupons/verify/new',
      });
      break;
    case 'searchOrder':
      uni.navigateTo({
        url: '/pages/groupons/order/index?showSearch=true',
      });
      break;
    case 'exportData':
      uni.showToast({
        title: '功能开发中',
        icon: 'none',
      });
      break;
  }
};

// 处理设置
const handleSettings = () => {
  uni.showToast({
    title: '设置功能开发中',
    icon: 'none',
  });
};

// 页面加载
onMounted(() => {
  loadOverviewData();
  loadTodayStats();
});

// 下拉刷新
const onPullDownRefresh = () => {
  Promise.all([
    loadOverviewData(),
    loadTodayStats(),
  ]).finally(() => {
    uni.stopPullDownRefresh();
  });
};

// 导出下拉刷新方法
defineExpose({
  onPullDownRefresh,
});
</script>

<style lang="scss" scoped>
.groupon-container {
  min-height: 100vh;
  background: linear-gradient(180deg, #1890FF 0%, #F0F9FF 30%);
}

.header {
  padding-top: var(--status-bar-height);
  background: linear-gradient(135deg, #1890FF 0%, #40A9FF 100%);
  
  .header-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 32rpx;
    
    .header-title {
      font-size: 36rpx;
      font-weight: 600;
      color: #fff;
    }
    
    .header-actions {
      display: flex;
      align-items: center;
    }
  }
}

.overview-section {
  margin: -20rpx 32rpx 32rpx;
  
  .overview-card {
    display: flex;
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    box-shadow: 0 4rpx 20rpx rgba(24, 144, 255, 0.1);
    
    .overview-item {
      flex: 1;
      display: flex;
      flex-direction: column;
      align-items: center;
      
      .overview-value {
        font-size: 32rpx;
        font-weight: 600;
        color: #1890FF;
        margin-bottom: 8rpx;
      }
      
      .overview-label {
        font-size: 24rpx;
        color: #666;
      }
    }
  }
}

.modules-section {
  padding: 0 32rpx 32rpx;
  
  .modules-grid {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 24rpx;
    
    .module-card {
      position: relative;
      background: #fff;
      border-radius: 16rpx;
      padding: 32rpx 24rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
      transition: all 0.3s ease;
      
      &:active {
        transform: scale(0.98);
        box-shadow: 0 1rpx 6rpx rgba(0, 0, 0, 0.1);
      }
      
      .module-icon {
        margin-bottom: 16rpx;
      }
      
      .module-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
      }
      
      .module-desc {
        font-size: 24rpx;
        color: #999;
      }
      
      .module-badge {
        position: absolute;
        top: 16rpx;
        right: 16rpx;
        background: #FF4D4F;
        border-radius: 20rpx;
        padding: 4rpx 12rpx;
        
        .badge-text {
          font-size: 20rpx;
          color: #fff;
        }
      }
    }
  }
}

.quick-actions {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .actions-scroll {
    white-space: nowrap;
    
    .actions-list {
      display: flex;
      gap: 24rpx;
      padding-bottom: 16rpx;
      
      .action-item {
        flex-shrink: 0;
        background: #fff;
        border-radius: 12rpx;
        padding: 24rpx 32rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        min-width: 120rpx;
        box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
        
        .action-icon {
          margin-bottom: 12rpx;
        }
        
        .action-text {
          font-size: 24rpx;
          color: #333;
          white-space: nowrap;
        }
      }
    }
  }
}

.today-stats {
  padding: 0 32rpx 32rpx;
  
  .section-title {
    font-size: 28rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 24rpx;
    display: block;
  }
  
  .stats-card {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    box-shadow: 0 2rpx 12rpx rgba(0, 0, 0, 0.05);
    
    .stats-row {
      display: flex;
      margin-bottom: 32rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
      
      .stats-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;
        
        .stats-label {
          font-size: 24rpx;
          color: #666;
          margin-bottom: 8rpx;
        }
        
        .stats-value {
          font-size: 28rpx;
          font-weight: 600;
          color: #1890FF;
        }
      }
    }
  }
}
</style>